import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource, Not } from "typeorm";
import { TalentStoneEntity } from "../entities/talent-stone.entity";
import { TalentStoneLevelEntity } from "../entities/talent-stone.entity";
import { TalentStoneBaseEntity } from "../entities/talent-stone.entity";
import { CharacterResourcesEntity } from "../entities/character-resources.entity";
import { CharacterEntity } from "../entities/character.entity";

@Injectable()
export class TalentStoneService {
  constructor(
    @InjectRepository(TalentStoneEntity)
    private readonly talentStoneRepository: Repository<TalentStoneEntity>,
    @InjectRepository(TalentStoneLevelEntity)
    private readonly talentStoneLevelRepository: Repository<TalentStoneLevelEntity>,
    @InjectRepository(TalentStoneBaseEntity)
    private readonly talentStoneBaseRepository: Repository<TalentStoneBaseEntity>,
    @InjectRepository(CharacterResourcesEntity)
    private readonly characterResourcesRepository: Repository<CharacterResourcesEntity>,
    private readonly dataSource: DataSource
  ) {}

  /**
   * 获取天赋石列表 (6035)
   */
  async getTalentStoneList(characterId: number, pageNum: number = 0) {
    try {
      const pageSize = 20;
      const offset = pageNum * pageSize;

      const [talentStones, total] =
        await this.talentStoneRepository.findAndCount({
          where: { characterId },
          skip: offset,
          take: pageSize,
          // 分页前排序：按等级从高到低，其次按ID从高到低
          order: { level: "DESC", id: "DESC" },
        });

      const list = talentStones.map((stone) => ({
        id: stone.id,
        lvl: stone.level,
        name: stone.name,
        num: stone.energy,
      }));

      return {
        act_id: 6035,
        code: 0,
        list,
        page: pageNum + 1,
        total,
      };
    } catch (error: any) {
      console.error("获取天赋石列表失败:", error);
      return {
        act_id: 6035,
        code: -1,
        msg: error?.message || "获取天赋石列表失败",
        list: [],
      };
    }
  }

  /**
   * 查看天赋石详情 (6184)
   */
  async getTalentStoneDetail(stoneId: number, characterId: number) {
    try {
      const talentStone = await this.talentStoneRepository.findOne({
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        return {
          act_id: 6184,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      // 获取等级元气数据
      const levelData = await this.talentStoneLevelRepository.findOne({
        where: { level: talentStone.level },
      });

      const data = {
        id: talentStone.id,
        name: talentStone.name,
        lvl: talentStone.level,
        e: talentStone.energy,
        eUp: levelData?.energy || 100,
        silver: levelData?.silverCost || 1000,
        state: talentStone.state,
        t: talentStone.type,
        type: talentStone.type,
        descr: talentStone.description || "",
        l: 0, // 锁定状态
        ss: 0, // 特殊状态
      };

      return {
        act_id: 6184,
        code: 0,
        data,
      };
    } catch (error: any) {
      console.error("获取天赋石详情失败:", error);
      return {
        act_id: 6184,
        code: -1,
        msg: error?.message || "获取天赋石详情失败",
      };
    }
  }

  /**
   * 获取角色已装备的天赋石列表（用于1000返回 stoneList）
   * state=2 表示已装备到角色
   */
  async getCharacterEquippedStones(characterId: number) {
    try {
      const stones = await this.talentStoneRepository.find({
        where: { characterId, state: 2 },
        order: { id: "DESC" },
      });
      return stones.map((s) => ({
        id: s.id,
        lvl: s.level,
        name: s.name,
        type: s.type,
        desc: s.description || "",
      }));
    } catch (error: any) {
      console.error("获取角色已装备天赋石失败:", error);
      return [];
    }
  }

  /**
   * 激活天赋石 (6186 act=3)
   */
  async activateTalentStone(stoneId: number, characterId: number) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const talentStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (talentStone.state !== 0) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石已激活",
        };
      }

      // 获取等级元气数据
      const levelData = await queryRunner.manager.findOne(
        TalentStoneLevelEntity,
        {
          where: { level: talentStone.level },
        }
      );

      const silverCost = levelData?.silverCost || 1000;

      // 检查银两是否足够
      const characterResources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (!characterResources || characterResources.silver < silverCost) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "银两不足",
        };
      }

      // 扣除银两
      characterResources.silver -= silverCost;
      await queryRunner.manager.save(
        CharacterResourcesEntity,
        characterResources
      );

      // 激活天赋石
      talentStone.state = 1;
      await queryRunner.manager.save(TalentStoneEntity, talentStone);

      await queryRunner.commitTransaction();

      return {
        act_id: 6186,
        code: 0,
        data: 3,
        msg: `成功激活${talentStone.name}`,
      };
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("激活天赋石失败:", error);
      return {
        act_id: 6186,
        code: -1,
        msg: error?.message || "激活天赋石失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 升级天赋石 (6186 act=5)
   */
  async upgradeTalentStone(stoneId: number, characterId: number) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const talentStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (talentStone.state === 0) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石未激活",
        };
      }

      // 获取下一级数据
      const nextLevelData = await queryRunner.manager.findOne(
        TalentStoneLevelEntity,
        {
          where: { level: talentStone.level + 1 },
        }
      );

      if (!nextLevelData) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "已达到最高等级",
        };
      }

      // 检查银两是否足够
      const characterResources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (
        !characterResources ||
        characterResources.silver < nextLevelData.silverCost
      ) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "银两不足",
        };
      }

      // 扣除银两
      characterResources.silver -= nextLevelData.silverCost;
      await queryRunner.manager.save(
        CharacterResourcesEntity,
        characterResources
      );

      // 升级天赋石
      talentStone.level += 1;
      talentStone.energy = nextLevelData.energy;
      await queryRunner.manager.save(TalentStoneEntity, talentStone);

      await queryRunner.commitTransaction();

      return {
        act_id: 6186,
        code: 0,
        data: 5,
        msg: "升级成功",
      };
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("升级天赋石失败:", error);
      return {
        act_id: 6186,
        code: -1,
        msg: error?.message || "升级天赋石失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 装备天赋石到角色 (6186 act=2)
   */
  async equipTalentStoneToCharacter(stoneId: number, characterId: number) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const talentStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (talentStone.state === 0) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石未激活",
        };
      }

      if (talentStone.state === 2) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石已装备",
        };
      }

      if (talentStone.state === 3) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石已装备到副将",
        };
      }

      // 检查同名天赋石是否已装备
      const existingStone = await queryRunner.manager.findOne(
        TalentStoneEntity,
        {
          where: { characterId, name: talentStone.name, state: 2 },
        }
      );

      if (existingStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: "同名天赋石已装备",
        };
      }

      // 校验角色身上已装备数量（按转职次数限定）
      // 未转: 1 个；一转: 2 个；二转及以上: 3 个
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: characterId },
      });
      const trans = character?.trans || 0;
      const limit = trans <= 0 ? 1 : trans === 1 ? 2 : 3;
      const equippedCount = await queryRunner.manager.count(TalentStoneEntity, {
        where: { characterId, state: 2 },
      });
      if (equippedCount >= limit) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6186,
          code: -1,
          msg: `角色可装备上限为${limit}个（当前转职：${trans}）`,
        };
      }

      // 装备天赋石
      talentStone.state = 2;
      await queryRunner.manager.save(TalentStoneEntity, talentStone);

      await queryRunner.commitTransaction();

      return {
        act_id: 6186,
        code: 0,
        data: 2,
        msg: `成功装备${talentStone.name}`,
      };
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("装备天赋石失败:", error);
      return {
        act_id: 6186,
        code: -1,
        msg: error?.message || "装备天赋石失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 卸下天赋石 (6186 act=1)
   */
  async unequipTalentStone(stoneId: number, characterId: number) {
    try {
      const talentStone = await this.talentStoneRepository.findOne({
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (talentStone.state !== 2) {
        return {
          act_id: 6186,
          code: -1,
          msg: "天赋石未装备",
        };
      }

      // 卸下天赋石
      talentStone.state = 1;
      await this.talentStoneRepository.save(talentStone);

      return {
        act_id: 6186,
        code: 0,
        data: 1,
        msg: `成功卸下${talentStone.name}`,
      };
    } catch (error: any) {
      console.error("卸下天赋石失败:", error);
      return {
        act_id: 6186,
        code: -1,
        msg: error?.message || "卸下天赋石失败",
      };
    }
  }

  /**
   * 获取可吸收的天赋石列表 (6189)
   */
  async getAbsorbableTalentStones(
    stoneId: number,
    characterId: number,
    pageNum: number = 0
  ) {
    try {
      const targetStone = await this.talentStoneRepository.findOne({
        where: { id: stoneId, characterId },
      });

      if (!targetStone) {
        return {
          act_id: 6189,
          code: -1,
          msg: "目标天赋石不存在",
        };
      }

      const pageSize = 20;
      const offset = pageNum * pageSize;

      // 获取其他可吸收的天赋石（排除目标天赋石）
      const [talentStones, total] =
        await this.talentStoneRepository.findAndCount({
          where: {
            characterId,
            id: Not(stoneId), // 排除目标天赋石
          },
          skip: offset,
          take: pageSize,
          order: { id: "DESC" },
        });

      const list = talentStones.map((stone) => ({
        id: stone.id,
        lvl: stone.level,
        name: stone.name,
        type: stone.type,
        energy: stone.energy,
      }));

      return {
        act_id: 6189,
        code: 0,
        list,
        page: pageNum + 1,
        total,
      };
    } catch (error: any) {
      console.error("获取可吸收天赋石列表失败:", error);
      return {
        act_id: 6189,
        code: -1,
        msg: error?.message || "获取可吸收天赋石列表失败",
        list: [],
      };
    }
  }

  /**
   * 吸收天赋石 (6185)
   */
  async absorbTalentStone(
    stoneId: number,
    absorbStoneId: number,
    characterId: number
  ) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const targetStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: stoneId, characterId },
      });

      const absorbStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: absorbStoneId, characterId },
      });

      if (!targetStone || !absorbStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6185,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (targetStone.id === absorbStone.id) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6185,
          code: -1,
          msg: "不能吸收自己",
        };
      }

      // 计算吸收的元气值
      let energyGained = 0;
      if (targetStone.name === absorbStone.name) {
        // 同名天赋石，获得大部分元气
        energyGained = Math.floor(absorbStone.energy * 0.8);
      } else {
        // 不同名天赋石，获得部分元气
        energyGained = Math.floor(absorbStone.energy * 0.3);
      }

      // 增加目标天赋石元气
      targetStone.energy += energyGained;
      await queryRunner.manager.save(TalentStoneEntity, targetStone);

      // 删除被吸收的天赋石
      await queryRunner.manager.remove(TalentStoneEntity, absorbStone);

      await queryRunner.commitTransaction();

      return {
        act_id: 6185,
        code: 0,
        msg: `${targetStone.name}吸收了${energyGained}魂元,被吸收魂蛋魂元耗尽破碎掉了`,
      };
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("吸收天赋石失败:", error);
      return {
        act_id: 6185,
        code: -1,
        msg: error?.message || "吸收天赋石失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 获取可装备的天赋石列表 (6188)
   * 根据文档，这个接口应该返回已激活但未装备的天赋石
   */
  async getEquippedTalentStones(
    characterId: number,
    deputyId: number = 0,
    pageNum: number = 0
  ) {
    try {
      const pageSize = 20;
      const offset = pageNum * pageSize;

      // 查询已激活但未装备的天赋石 (state: 1)
      let whereCondition: any = { characterId, state: 1 };
      if (deputyId > 0) {
        // 如果查询副将，则查询已激活且未装备到副将的天赋石
        whereCondition.deputyId = null;
      } else {
        // 如果查询角色，则查询已激活且未装备到角色的天赋石
        whereCondition.deputyId = null;
      }

      const [talentStones, total] =
        await this.talentStoneRepository.findAndCount({
          where: whereCondition,
          skip: offset,
          take: pageSize,
          order: { id: "DESC" },
        });

      const list = talentStones.map((stone) => ({
        id: stone.id,
        lvl: stone.level,
        name: stone.name,
        type: stone.type,
        desc: stone.description || "",
      }));

      return {
        act_id: 6188,
        code: 0,
        list,
        page: pageNum + 1,
        total,
      };
    } catch (error: any) {
      console.error("获取可装备天赋石列表失败:", error);
      return {
        act_id: 6188,
        code: -1,
        msg: error?.message || "获取可装备天赋石列表失败",
        list: [],
      };
    }
  }

  /**
   * 装备天赋石到副将 (6187)
   */
  async equipTalentStoneToDeputy(
    stoneId: number,
    deputyId: number,
    characterId: number,
    action: string
  ) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const talentStone = await queryRunner.manager.findOne(TalentStoneEntity, {
        where: { id: stoneId, characterId },
      });

      if (!talentStone) {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6187,
          code: -1,
          msg: "天赋石不存在",
        };
      }

      if (action === "2") {
        // 装备到副将
        if (talentStone.state !== 1) {
          await queryRunner.rollbackTransaction();
          return {
            act_id: 6187,
            code: -1,
            msg: "天赋石未激活",
          };
        }

        // 校验副将身上已装备数量（按角色转职次数限定）
        // 未转: 1 个；一转: 2 个；二转及以上: 3 个
        const character = await queryRunner.manager.findOne(CharacterEntity, {
          where: { id: characterId },
        });
        const trans = character?.trans || 0;
        const limit = trans <= 0 ? 1 : trans === 1 ? 2 : 3;

        const equippedCount = await queryRunner.manager.count(
          TalentStoneEntity,
          {
            where: { characterId, deputyId, state: 3 },
          }
        );

        if (equippedCount >= limit) {
          await queryRunner.rollbackTransaction();
          return {
            act_id: 6187,
            code: -1,
            msg: `副将可装备上限为${limit}个（当前转职：${trans}）`,
          };
        }

        // 检查同名天赋石是否已装备到该副将
        const existingStone = await queryRunner.manager.findOne(
          TalentStoneEntity,
          {
            where: { characterId, deputyId, name: talentStone.name, state: 3 },
          }
        );

        if (existingStone) {
          await queryRunner.rollbackTransaction();
          return {
            act_id: 6187,
            code: -1,
            msg: "同名天赋石已装备到该副将",
          };
        }

        talentStone.state = 3;
        talentStone.deputyId = deputyId;
        await queryRunner.manager.save(TalentStoneEntity, talentStone);

        await queryRunner.commitTransaction();

        return {
          act_id: 6187,
          code: 0,
          data: 2,
          msg: "成功装备魂蛋",
        };
      } else if (action === "1") {
        // 从副将卸下
        if (talentStone.state !== 3 || talentStone.deputyId !== deputyId) {
          await queryRunner.rollbackTransaction();
          return {
            act_id: 6187,
            code: -1,
            msg: "天赋石未装备到该副将",
          };
        }

        talentStone.state = 1;
        talentStone.deputyId = undefined;
        await queryRunner.manager.save(TalentStoneEntity, talentStone);

        await queryRunner.commitTransaction();

        return {
          act_id: 6187,
          code: 0,
          data: 1,
          msg: "成功卸下魂蛋",
        };
      } else {
        await queryRunner.rollbackTransaction();
        return {
          act_id: 6187,
          code: -1,
          msg: "无效的操作",
        };
      }
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("副将天赋石操作失败:", error);
      return {
        act_id: 6187,
        code: -1,
        msg: error?.message || "副将天赋石操作失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 为角色创建随机1级天赋石（月卡奖励用）
   * @param characterId 角色ID
   * @param count 创建数量
   * @returns 创建的天赋石列表
   */
  async createRandomTalentStones(
    characterId: number,
    count: number
  ): Promise<TalentStoneEntity[]> {
    try {
      // 获取所有可用的天赋石基础配置
      const talentStoneBases = await this.talentStoneBaseRepository.find();

      if (talentStoneBases.length === 0) {
        console.warn("没有可用的天赋石基础配置");
        return [];
      }

      const createdStones: TalentStoneEntity[] = [];

      for (let i = 0; i < count; i++) {
        // 随机选择一个天赋石类型
        const randomIndex = Math.floor(Math.random() * talentStoneBases.length);
        const selectedBase = talentStoneBases[randomIndex];

        // 创建1级天赋石
        const talentStone = new TalentStoneEntity();
        talentStone.characterId = characterId;
        talentStone.name = selectedBase.name;
        talentStone.level = 1;
        talentStone.energy = 100; // 1级天赋石默认100元气
        talentStone.type = selectedBase.typeId;
        talentStone.state = 0; // 未激活状态
        talentStone.description = selectedBase.description;

        const savedStone = await this.talentStoneRepository.save(talentStone);
        createdStones.push(savedStone);
      }

      console.log(`为角色${characterId}创建了${count}个随机1级天赋石`);
      return createdStones;
    } catch (error: any) {
      console.error("创建随机天赋石失败:", error);
      throw new Error(`创建随机天赋石失败: ${error?.message || error}`);
    }
  }
}
